using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;

namespace MatrixFramework.Shared.Domain.Photos.Processing
{
    /// <summary>
    /// 照片处理任务实体
    /// 支持各种图像处理任务的调度和执行
    /// </summary>
    public class PhotoProcessing : FullAuditedAggregateRoot<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public virtual Guid? TenantId { get; protected set; }

        /// <summary>
        /// 照片ID
        /// </summary>
        public virtual Guid PhotoId { get; protected set; }

        /// <summary>
        /// 处理类型
        /// </summary>
        public virtual ProcessingType ProcessingType { get; protected set; }

        /// <summary>
        /// 处理状态
        /// </summary>
        public virtual ProcessingStatus Status { get; protected set; }

        /// <summary>
        /// 处理优先级
        /// </summary>
        public virtual ProcessingPriority Priority { get; protected set; }

        /// <summary>
        /// 处理参数
        /// </summary>
        public virtual Dictionary<string, object> Parameters { get; protected set; }

        /// <summary>
        /// 输入文件路径
        /// </summary>
        [MaxLength(1000)]
        public virtual string InputPath { get; protected set; }

        /// <summary>
        /// 输出文件路径
        /// </summary>
        [MaxLength(1000)]
        public virtual string OutputPath { get; protected set; }

        /// <summary>
        /// 处理引擎
        /// </summary>
        [MaxLength(100)]
        public virtual string Engine { get; protected set; }

        /// <summary>
        /// 引擎版本
        /// </summary>
        [MaxLength(50)]
        public virtual string EngineVersion { get; protected set; }

        /// <summary>
        /// 计划执行时间
        /// </summary>
        public virtual DateTime? ScheduledTime { get; protected set; }

        /// <summary>
        /// 开始执行时间
        /// </summary>
        public virtual DateTime? StartTime { get; protected set; }

        /// <summary>
        /// 完成时间
        /// </summary>
        public virtual DateTime? CompletionTime { get; protected set; }

        /// <summary>
        /// 执行耗时（毫秒）
        /// </summary>
        public virtual long Duration { get; protected set; }

        /// <summary>
        /// 超时时间（分钟）
        /// </summary>
        public virtual int TimeoutMinutes { get; protected set; }

        /// <summary>
        /// 重试次数
        /// </summary>
        public virtual int RetryCount { get; protected set; }

        /// <summary>
        /// 最大重试次数
        /// </summary>
        public virtual int MaxRetryCount { get; protected set; }

        /// <summary>
        /// 进度百分比
        /// </summary>
        public virtual double ProgressPercentage { get; protected set; }

        /// <summary>
        /// 当前处理步骤
        /// </summary>
        [MaxLength(200)]
        public virtual string CurrentStep { get; protected set; }

        /// <summary>
        /// 错误消息
        /// </summary>
        [MaxLength(2000)]
        public virtual string ErrorMessage { get; protected set; }

        /// <summary>
        /// 错误详情
        /// </summary>
        public virtual Dictionary<string, object> ErrorDetails { get; protected set; }

        /// <summary>
        /// 处理结果
        /// </summary>
        public virtual ProcessingResult Result { get; protected set; }

        /// <summary>
        /// 处理统计
        /// </summary>
        public virtual ProcessingStatistics Statistics { get; protected set; }

        /// <summary>
        /// 处理配置
        /// </summary>
        public virtual ProcessingConfiguration Configuration { get; protected set; }

        /// <summary>
        /// 处理日志
        /// </summary>
        public virtual List<ProcessingLog> Logs { get; protected set; }

        /// <summary>
        /// 照片导航属性
        /// </summary>
        public virtual Photo Photo { get; protected set; }

        protected PhotoProcessing()
        {
            Parameters = new Dictionary<string, object>();
            ErrorDetails = new Dictionary<string, object>();
            Result = new ProcessingResult();
            Statistics = new ProcessingStatistics();
            Configuration = new ProcessingConfiguration();
            Logs = new List<ProcessingLog>();
        }

        public PhotoProcessing(
            Guid id,
            Guid photoId,
            ProcessingType processingType,
            Dictionary<string, object> parameters = null,
            string engine = "Default",
            Guid? tenantId = null) : base(id)
        {
            PhotoId = photoId;
            ProcessingType = processingType;
            Parameters = parameters ?? new Dictionary<string, object>();
            Engine = engine;
            TenantId = tenantId;
            Status = ProcessingStatus.Pending;
            Priority = ProcessingPriority.Normal;
            TimeoutMinutes = 30;
            MaxRetryCount = 3;

            ErrorDetails = new Dictionary<string, object>();
            Result = new ProcessingResult();
            Statistics = new ProcessingStatistics();
            Configuration = new ProcessingConfiguration();
            Logs = new List<ProcessingLog>();
        }

        /// <summary>
        /// 开始处理
        /// </summary>
        public virtual void StartProcessing()
        {
            if (Status != ProcessingStatus.Pending && Status != ProcessingStatus.Retrying)
                throw new InvalidOperationException($"无法在状态 {Status} 下开始处理");

            Status = ProcessingStatus.Running;
            StartTime = DateTime.Now;
            ProgressPercentage = 0;
            CurrentStep = "开始处理";
            AddLog(ProcessingLogLevel.Info, "开始处理", $"处理类型: {ProcessingType}");
        }

        /// <summary>
        /// 完成处理
        /// </summary>
        public virtual void CompleteProcessing(bool success, ProcessingResult result = null)
        {
            CompletionTime = DateTime.Now;
            if (StartTime.HasValue)
            {
                Duration = (long)(CompletionTime.Value - StartTime.Value).TotalMilliseconds;
            }

            ProgressPercentage = 100;
            CurrentStep = "处理完成";

            if (success)
            {
                Status = ProcessingStatus.Completed;
                Result = result ?? new ProcessingResult { IsSuccess = true };
                AddLog(ProcessingLogLevel.Info, "处理完成", $"耗时: {Duration}ms");
            }
            else
            {
                Status = ProcessingStatus.Failed;
                Result.IsSuccess = false;
                AddLog(ProcessingLogLevel.Error, "处理失败", ErrorMessage);
            }

            Statistics.UpdateStatistics(this);
        }

        /// <summary>
        /// 取消处理
        /// </summary>
        public virtual void CancelProcessing(string reason = null)
        {
            Status = ProcessingStatus.Cancelled;
            CompletionTime = DateTime.Now;
            if (StartTime.HasValue)
            {
                Duration = (long)(CompletionTime.Value - StartTime.Value).TotalMilliseconds;
            }
            CurrentStep = "已取消";
            AddLog(ProcessingLogLevel.Warning, "处理已取消", reason);
        }

        /// <summary>
        /// 暂停处理
        /// </summary>
        public virtual void PauseProcessing(string reason = null)
        {
            if (Status != ProcessingStatus.Running)
                throw new InvalidOperationException($"无法在状态 {Status} 下暂停处理");

            Status = ProcessingStatus.Paused;
            CurrentStep = "已暂停";
            AddLog(ProcessingLogLevel.Info, "处理已暂停", reason);
        }

        /// <summary>
        /// 恢复处理
        /// </summary>
        public virtual void ResumeProcessing()
        {
            if (Status != ProcessingStatus.Paused)
                throw new InvalidOperationException($"无法在状态 {Status} 下恢复处理");

            Status = ProcessingStatus.Running;
            CurrentStep = "继续处理";
            AddLog(ProcessingLogLevel.Info, "处理已恢复");
        }

        /// <summary>
        /// 重试处理
        /// </summary>
        public virtual void RetryProcessing()
        {
            if (RetryCount >= MaxRetryCount)
            {
                CompleteProcessing(false, "已达到最大重试次数");
                return;
            }

            RetryCount++;
            Status = ProcessingStatus.Retrying;
            StartTime = DateTime.Now;
            ProgressPercentage = 0;
            ErrorMessage = null;
            ErrorDetails.Clear();
            CurrentStep = "重试处理";
            AddLog(ProcessingLogLevel.Info, "开始重试处理", $"重试次数: {RetryCount}/{MaxRetryCount}");
        }

        /// <summary>
        /// 更新进度
        /// </summary>
        public virtual void UpdateProgress(double percentage, string currentStep = null)
        {
            ProgressPercentage = Math.Max(0, Math.Min(100, percentage));
            if (!string.IsNullOrWhiteSpace(currentStep))
            {
                CurrentStep = currentStep;
            }

            if (ProgressPercentage >= 100)
            {
                CompleteProcessing(true);
            }
        }

        /// <summary>
        /// 设置错误信息
        /// </summary>
        public virtual void SetError(string errorMessage, Dictionary<string, object> errorDetails = null)
        {
            ErrorMessage = errorMessage;
            ErrorDetails = errorDetails ?? new Dictionary<string, object>();
            CurrentStep = "处理出错";
            AddLog(ProcessingLogLevel.Error, errorMessage);
        }

        /// <summary>
        /// 更新参数
        /// </summary>
        public virtual void UpdateParameters(Dictionary<string, object> parameters)
        {
            Parameters = parameters ?? new Dictionary<string, object>();
        }

        /// <summary>
        /// 设置参数
        /// </summary>
        public virtual void SetParameter(string key, object value)
        {
            Parameters[key] = value;
        }

        /// <summary>
        /// 设置输入路径
        /// </summary>
        public virtual void SetInputPath(string inputPath)
        {
            InputPath = inputPath;
        }

        /// <summary>
        /// 设置输出路径
        /// </summary>
        public virtual void SetOutputPath(string outputPath)
        {
            OutputPath = outputPath;
        }

        /// <summary>
        /// 设置引擎信息
        /// </summary>
        public virtual void SetEngineInfo(string engine, string version = null)
        {
            Engine = engine;
            EngineVersion = version;
        }

        /// <summary>
        /// 设置计划执行时间
        /// </summary>
        public virtual void SetScheduledTime(DateTime scheduledTime)
        {
            ScheduledTime = scheduledTime;
        }

        /// <summary>
        /// 更新处理结果
        /// </summary>
        public virtual void UpdateResult(ProcessingResult result)
        {
            Result = result ?? new ProcessingResult();
        }

        /// <summary>
        /// 更新配置
        /// </summary>
        public virtual void UpdateConfiguration(ProcessingConfiguration configuration)
        {
            Configuration = configuration ?? new ProcessingConfiguration();
        }

        /// <summary>
        /// 添加处理日志
        /// </summary>
        public virtual void AddLog(ProcessingLogLevel level, string message, string details = null)
        {
            var log = new ProcessingLog
            {
                Level = level,
                Message = message,
                Details = details,
                LogTime = DateTime.Now,
                ProgressPercentage = ProgressPercentage,
                CurrentStep = CurrentStep
            };

            Logs.Add(log);
        }

        /// <summary>
        /// 检查是否超时
        /// </summary>
        public virtual bool IsTimeout()
        {
            if (!StartTime.HasValue || TimeoutMinutes <= 0)
                return false;

            return DateTime.Now > StartTime.Value.AddMinutes(TimeoutMinutes);
        }

        /// <summary>
        /// 检查是否可以重试
        /// </summary>
        public virtual bool CanRetry()
        {
            return RetryCount < MaxRetryCount &&
                   (Status == ProcessingStatus.Failed || Status == ProcessingStatus.Timeout);
        }

        /// <summary>
        /// 获取执行耗时
        /// </summary>
        public virtual TimeSpan? GetExecutionDuration()
        {
            if (!StartTime.HasValue)
                return null;

            var endTime = CompletionTime ?? DateTime.Now;
            return endTime - StartTime.Value;
        }
    }

    /// <summary>
    /// 处理类型枚举
    /// </summary>
    public enum ProcessingType
    {
        /// <summary>
        /// 生成缩略图
        /// </summary>
        ThumbnailGeneration = 0,

        /// <summary>
        /// 图片压缩
        /// </summary>
        Compression = 1,

        /// <summary>
        /// 格式转换
        /// </summary>
        FormatConversion = 2,

        /// <summary>
        /// 图片旋转
        /// </summary>
        Rotation = 3,

        /// <summary>
        /// 图片裁剪
        /// </summary>
        Cropping = 4,

        /// <summary>
        /// 图片缩放
        /// </summary>
        Resizing = 5,

        /// <summary>
        /// 水印添加
        /// </summary>
        Watermarking = 6,

        /// <summary>
        /// 颜色调整
        /// </summary>
        ColorAdjustment = 7,

        /// <summary>
        /// 滤镜效果
        /// </summary>
        Filtering = 8,

        /// <summary>
        /// 人脸检测
        /// </summary>
        FaceDetection = 9,

        /// <summary>
        /// 人脸识别
        /// </summary>
        FaceRecognition = 10,

        /// <summary>
        /// 场景识别
        /// </summary>
        SceneRecognition = 11,

        /// <summary>
        /// 物体检测
        /// </summary>
        ObjectDetection = 12,

        /// <summary>
        /// 文字识别
        /// </summary>
        TextRecognition = 13,

        /// <summary>
        /// 元数据提取
        /// </summary>
        MetadataExtraction = 14,

        /// <summary>
        /// 质量评估
        /// </summary>
        QualityAssessment = 15,

        /// <summary>
        /// 相似度计算
        /// </summary>
        SimilarityCalculation = 16,

        /// <summary>
        /// 背景移除
        /// </summary>
        BackgroundRemoval = 17,

        /// <summary>
        /// 图片增强
        /// </summary>
        Enhancement = 18,

        /// <summary>
        /// 降噪处理
        /// </summary>
        Denoising = 19,

        /// <summary>
        /// 锐化处理
        /// </summary>
        Sharpening = 20,

        /// <summary>
        /// 自动重命名
        /// </summary>
        AutoRename = 21,

        /// <summary>
        /// 病毒扫描
        /// </summary>
        VirusScanning = 22,

        /// <summary>
        /// 完整性验证
        /// </summary>
        IntegrityValidation = 23,

        /// <summary>
        /// 自定义处理
        /// </summary>
        CustomProcessing = 24
    }

    /// <summary>
    /// 处理状态枚举
    /// </summary>
    public enum ProcessingStatus
    {
        /// <summary>
        /// 等待中
        /// </summary>
        Pending = 0,

        /// <summary>
        /// 运行中
        /// </summary>
        Running = 1,

        /// <summary>
        /// 已暂停
        /// </summary>
        Paused = 2,

        /// <summary>
        /// 已完成
        /// </summary>
        Completed = 3,

        /// <summary>
        /// 失败
        /// </summary>
        Failed = 4,

        /// <summary>
        /// 已取消
        /// </summary>
        Cancelled = 5,

        /// <summary>
        /// 重试中
        /// </summary>
        Retrying = 6,

        /// <summary>
        /// 超时
        /// </summary>
        Timeout = 7
    }

    /// <summary>
    /// 处理优先级枚举
    /// </summary>
    public enum ProcessingPriority
    {
        /// <summary>
        /// 低优先级
        /// </summary>
        Low = 0,

        /// <summary>
        /// 普通优先级
        /// </summary>
        Normal = 1,

        /// <summary>
        /// 高优先级
        /// </summary>
        High = 2,

        /// <summary>
        /// 紧急优先级
        /// </summary>
        Urgent = 3,

        /// <summary>
        /// 实时优先级
        /// </summary>
        RealTime = 4
    }

    /// <summary>
    /// 处理结果
    /// </summary>
    public class ProcessingResult
    {
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool IsSuccess { get; set; }

        /// <summary>
        /// 输出文件列表
        /// </summary>
        public List<string> OutputFiles { get; set; } = new();

        /// <summary>
        /// 处理后的文件大小
        /// </summary>
        public long OutputFileSize { get; set; }

        /// <summary>
        /// 压缩比例
        /// </summary>
        public double CompressionRatio { get; set; }

        /// <summary>
        /// 质量评分
        /// </summary>
        public double QualityScore { get; set; }

        /// <summary>
        /// 处理数据
        /// </summary>
        public Dictionary<string, object> Data { get; set; } = new();

        /// <summary>
        /// 性能指标
        /// </summary>
        public ProcessingMetrics Metrics { get; set; } = new();

        /// <summary>
        /// 处理后的元数据
        /// </summary>
        public Dictionary<string, object> ProcessedMetadata { get; set; } = new();

        /// <summary>
        /// 警告信息
        /// </summary>
        public List<string> Warnings { get; set; } = new();
    }

    /// <summary>
    /// 处理性能指标
    /// </summary>
    public class ProcessingMetrics
    {
        /// <summary>
        /// CPU使用时间（毫秒）
        /// </summary>
        public long CpuTimeMs { get; set; }

        /// <summary>
        /// 内存使用量（字节）
        /// </summary>
        public long MemoryUsage { get; set; }

        /// <summary>
        /// 磁盘读取量（字节）
        /// </summary>
        public long DiskReadBytes { get; set; }

        /// <summary>
        /// 磁盘写入量（字节）
        /// </summary>
        public long DiskWriteBytes { get; set; }

        /// <summary>
        /// 网络传输量（字节）
        /// </summary>
        public long NetworkTransferBytes { get; set; }

        /// <summary>
        /// 处理速度（像素/秒）
        /// </summary>
        public double ProcessingSpeedPixelsPerSecond { get; set; }

        /// <summary>
        /// 算法复杂度
        /// </summary>
        public string AlgorithmicComplexity { get; set; }

        /// <summary>
        /// 缓存命中率
        /// </summary>
        public double CacheHitRate { get; set; }
    }

    /// <summary>
    /// 处理统计
    /// </summary>
    public class ProcessingStatistics
    {
        /// <summary>
        /// 总处理次数
        /// </summary>
        public int TotalProcessings { get; set; }

        /// <summary>
        /// 成功次数
        /// </summary>
        public int SuccessCount { get; set; }

        /// <summary>
        /// 失败次数
        /// </summary>
        public int FailureCount { get; set; }

        /// <summary>
        /// 平均执行时间（毫秒）
        /// </summary>
        public double AverageExecutionTimeMs { get; set; }

        /// <summary>
        /// 最小执行时间（毫秒）
        /// </summary>
        public long MinExecutionTimeMs { get; set; }

        /// <summary>
        /// 最大执行时间（毫秒）
        /// </summary>
        public long MaxExecutionTimeMs { get; set; }

        /// <summary>
        /// 总处理数据量（字节）
        /// </summary>
        public long TotalProcessedBytes { get; set; }

        /// <summary>
        /// 最后处理时间
        /// </summary>
        public DateTime? LastProcessingTime { get; set; }

        /// <summary>
        /// 成功率
        /// </summary>
        public double SuccessRate => TotalProcessings > 0 ? (double)SuccessCount / TotalProcessings : 0;

        /// <summary>
        /// 更新统计信息
        /// </summary>
        public void UpdateStatistics(PhotoProcessing processing)
        {
            TotalProcessings++;

            if (processing.Status == ProcessingStatus.Completed)
            {
                SuccessCount++;
            }
            else
            {
                FailureCount++;
            }

            if (processing.Duration > 0)
            {
                AverageExecutionTimeMs = (AverageExecutionTimeMs * (TotalProcessings - 1) + processing.Duration) / TotalProcessings;

                if (MinExecutionTimeMs == 0 || processing.Duration < MinExecutionTimeMs)
                    MinExecutionTimeMs = processing.Duration;

                if (processing.Duration > MaxExecutionTimeMs)
                    MaxExecutionTimeMs = processing.Duration;
            }

            LastProcessingTime = processing.CompletionTime ?? DateTime.Now;
        }
    }

    /// <summary>
    /// 处理配置
    /// </summary>
    public class ProcessingConfiguration
    {
        /// <summary>
        /// 是否启用并行处理
        /// </summary>
        public bool EnableParallelProcessing { get; set; } = false;

        /// <summary>
        /// 并行线程数
        /// </summary>
        public int ParallelThreadCount { get; set; } = 1;

        /// <summary>
        /// 是否启用缓存
        /// </summary>
        public bool EnableCache { get; set; } = true;

        /// <summary>
        /// 缓存有效期（分钟）
        /// </summary>
        public int CacheExpiryMinutes { get; set; } = 60;

        /// <summary>
        /// 是否启用进度报告
        /// </summary>
        public bool EnableProgressReporting { get; set; } = true;

        /// <summary>
        /// 进度报告间隔（百分比）
        /// </summary>
        public int ProgressReportInterval { get; set; } = 10;

        /// <summary>
        /// 是否启用详细日志
        /// </summary>
        public bool EnableDetailedLogging { get; set; } = true;

        /// <summary>
        /// 最大日志条数
        /// </summary>
        public int MaxLogEntries { get; set; } = 1000;

        /// <summary>
        /// 是否启用自动重试
        /// </summary>
        public bool EnableAutoRetry { get; set; } = true;

        /// <summary>
        /// 重试延迟（毫秒）
        /// </summary>
        public int RetryDelayMs { get; set; } = 1000;

        /// <summary>
        /// 资源限制
        /// </summary>
        public ProcessingResourceLimits ResourceLimits { get; set; } = new();

        /// <summary>
        /// 质量设置
        /// </summary>
        public QualitySettings QualitySettings { get; set; } = new();
    }

    /// <summary>
    /// 处理资源限制
    /// </summary>
    public class ProcessingResourceLimits
    {
        /// <summary>
        /// 最大内存使用量（MB）
        /// </summary>
        public long MaxMemoryMB { get; set; } = 512;

        /// <summary>
        /// 最大CPU使用率（百分比）
        /// </summary>
        public double MaxCpuUsage { get; set; } = 80;

        /// <summary>
        /// 最大处理时间（分钟）
        /// </summary>
        public int MaxProcessingTimeMinutes { get; set; } = 30;

        /// <summary>
        /// 最大文件大小（MB）
        /// </summary>
        public long MaxFileSizeMB { get; set; } = 100;
    }

    /// <summary>
    /// 质量设置
    /// </summary>
    public class QualitySettings
    {
        /// <summary>
        /// JPEG质量（0-100）
        /// </summary>
        public int JpegQuality { get; set; } = 85;

        /// <summary>
        /// PNG压缩级别（0-9）
        /// </summary>
        public int PngCompressionLevel { get; set; } = 6;

        /// <summary>
        /// WebP质量（0-100）
        /// </summary>
        public int WebPQuality { get; set; } = 80;

        /// <summary>
        /// 是否保持原始质量
        /// </summary>
        public bool PreserveOriginalQuality { get; set; } = false;

        /// <summary>
        /// 是否启用无损压缩
        /// </summary>
        public bool EnableLosslessCompression { get; set; } = false;

        /// <summary>
        /// 质量阈值
        /// </summary>
        public double QualityThreshold { get; set; } = 0.8;
    }

    /// <summary>
    /// 处理日志
    /// </summary>
    public class ProcessingLog
    {
        /// <summary>
        /// 日志级别
        /// </summary>
        public ProcessingLogLevel Level { get; set; }

        /// <summary>
        /// 日志消息
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// 详细信息
        /// </summary>
        public string Details { get; set; }

        /// <summary>
        /// 日志时间
        /// </summary>
        public DateTime LogTime { get; set; }

        /// <summary>
        /// 进度百分比
        /// </summary>
        public double ProgressPercentage { get; set; }

        /// <summary>
        /// 当前步骤
        /// </summary>
        public string CurrentStep { get; set; }

        /// <summary>
        /// 处理耗时（毫秒）
        /// </summary>
        public long? ProcessingTimeMs { get; set; }

        /// <summary>
        /// 内存使用量（字节）
        /// </summary>
        public long? MemoryUsage { get; set; }

        /// <summary>
        /// 额外数据
        /// </summary>
        public Dictionary<string, object> AdditionalData { get; set; } = new();
    }

    /// <summary>
    /// 处理日志级别枚举
    /// </summary>
    public enum ProcessingLogLevel
    {
        /// <summary>
        /// 调试
        /// </summary>
        Debug = 0,

        /// <summary>
        /// 信息
        /// </summary>
        Info = 1,

        /// <summary>
        /// 警告
        /// </summary>
        Warning = 2,

        /// <summary>
        /// 错误
        /// </summary>
        Error = 3,

        /// <summary>
        /// 致命错误
        /// </summary>
        Fatal = 4
    }

    /// <summary>
    /// 照片处理模板
    /// </summary>
    public class PhotoProcessingTemplate : FullAuditedAggregateRoot<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public virtual Guid? TenantId { get; protected set; }

        /// <summary>
        /// 模板名称
        /// </summary>
        [Required]
        [MaxLength(200)]
        public virtual string Name { get; protected set; }

        /// <summary>
        /// 模板描述
        /// </summary>
        [MaxLength(1000)]
        public virtual string Description { get; protected set; }

        /// <summary>
        /// 模板类型
        /// </summary>
        public virtual TemplateType TemplateType { get; protected set; }

        /// <summary>
        /// 是否为系统模板
        /// </summary>
        public virtual bool IsSystem { get; protected set; }

        /// <summary>
        /// 是否启用
        /// </summary>
        public virtual bool IsEnabled { get; protected set; }

        /// <summary>
        /// 处理步骤列表
        /// </summary>
        public virtual List<ProcessingStep> Steps { get; protected set; }

        /// <summary>
        /// 默认参数
        /// </summary>
        public virtual Dictionary<string, object> DefaultParameters { get; protected set; }

        /// <summary>
        /// 模板配置
        /// </summary>
        public virtual TemplateConfiguration Configuration { get; protected set; }

        /// <summary>
        /// 使用统计
        /// </summary>
        public virtual TemplateUsage Usage { get; protected set; }

        protected PhotoProcessingTemplate()
        {
            Steps = new List<ProcessingStep>();
            DefaultParameters = new Dictionary<string, object>();
            Configuration = new TemplateConfiguration();
            Usage = new TemplateUsage();
        }

        public PhotoProcessingTemplate(
            Guid id,
            string name,
            string description = null,
            TemplateType templateType = TemplateType.Custom,
            bool isSystem = false,
            Guid? tenantId = null) : base(id)
        {
            Name = name;
            Description = description;
            TemplateType = templateType;
            IsSystem = isSystem;
            TenantId = tenantId;
            IsEnabled = true;

            Steps = new List<ProcessingStep>();
            DefaultParameters = new Dictionary<string, object>();
            Configuration = new TemplateConfiguration();
            Usage = new TemplateUsage();
        }

        /// <summary>
        /// 添加处理步骤
        /// </summary>
        public virtual void AddStep(ProcessingStep step)
        {
            if (step != null)
            {
                step.Order = Steps.Count;
                Steps.Add(step);
            }
        }

        /// <summary>
        /// 移除处理步骤
        /// </summary>
        public virtual void RemoveStep(int stepIndex)
        {
            if (stepIndex >= 0 && stepIndex < Steps.Count)
            {
                Steps.RemoveAt(stepIndex);
                // 重新排序
                for (int i = 0; i < Steps.Count; i++)
                {
                    Steps[i].Order = i;
                }
            }
        }

        /// <summary>
        /// 更新处理步骤
        /// </summary>
        public virtual void UpdateSteps(List<ProcessingStep> steps)
        {
            Steps = steps ?? new List<ProcessingStep>();
            for (int i = 0; i < Steps.Count; i++)
            {
                Steps[i].Order = i;
            }
        }

        /// <summary>
        /// 更新默认参数
        /// </summary>
        public virtual void UpdateDefaultParameters(Dictionary<string, object> parameters)
        {
            DefaultParameters = parameters ?? new Dictionary<string, object>();
        }

        /// <summary>
        /// 设置默认参数
        /// </summary>
        public virtual void SetDefaultParameter(string key, object value)
        {
            DefaultParameters[key] = value;
        }

        /// <summary>
        /// 启用模板
        /// </summary>
        public virtual void Enable()
        {
            IsEnabled = true;
        }

        /// <summary>
        /// 禁用模板
        /// </summary>
        public virtual void Disable()
        {
            IsEnabled = false;
        }

        /// <summary>
        /// 记录使用
        /// </summary>
        public virtual void RecordUsage()
        {
            Usage.TotalUsageCount++;
            Usage.LastUsedTime = DateTime.Now;
        }

        /// <summary>
        /// 检查是否可以使用
        /// </summary>
        public virtual bool CanUse()
        {
            return IsEnabled && Steps.Count > 0;
        }
    }

    /// <summary>
    /// 模板类型枚举
    /// </summary>
    public enum TemplateType
    {
        /// <summary>
        /// 自定义模板
        /// </summary>
        Custom = 0,

        /// <summary>
        /// 系统模板
        /// </summary>
        System = 1,

        /// <summary>
        /// 预设模板
        /// </summary>
        Preset = 2,

        /// <summary>
        /// 用户模板
        /// </summary>
        User = 3
    }

    /// <summary>
    /// 处理步骤
    /// </summary>
    public class ProcessingStep
    {
        /// <summary>
        /// 步骤ID
        /// </summary>
        public Guid Id { get; set; } = Guid.NewGuid();

        /// <summary>
        /// 步骤名称
        /// </summary>
        [Required]
        [MaxLength(200)]
        public string Name { get; set; }

        /// <summary>
        /// 步骤描述
        /// </summary>
        [MaxLength(1000)]
        public string Description { get; set; }

        /// <summary>
        /// 处理类型
        /// </summary>
        public ProcessingType ProcessingType { get; set; }

        /// <summary>
        /// 步骤顺序
        /// </summary>
        public int Order { get; set; }

        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnabled { get; set; } = true;

        /// <summary>
        /// 是否必需
        /// </summary>
        public bool IsRequired { get; set; } = true;

        /// <summary>
        /// 步骤参数
        /// </summary>
        public Dictionary<string, object> Parameters { get; set; } = new();

        /// <summary>
        /// 失败时是否继续
        /// </summary>
        public bool ContinueOnFailure { get; set; } = false;

        /// <summary>
        /// 重试次数
        /// </summary>
        public int RetryCount { get; set; } = 0;

        /// <summary>
        /// 超时时间（分钟）
        /// </summary>
        public int TimeoutMinutes { get; set; } = 10;

        /// <summary>
        /// 依赖步骤列表
        /// </summary>
        public List<Guid> DependentStepIds { get; set; } = new();
    }

    /// <summary>
    /// 模板配置
    /// </summary>
    public class TemplateConfiguration
    {
        /// <summary>
        /// 是否允许并行执行
        /// </summary>
        public bool AllowParallelExecution { get; set; } = false;

        /// <summary>
        /// 最大并行步骤数
        /// </summary>
        public int MaxParallelSteps { get; set; } = 1;

        /// <summary>
        /// 是否启用步骤跳过
        /// </summary>
        public bool EnableStepSkipping { get; set; } = false;

        /// <summary>
        /// 是否启用断点续传
        /// </summary>
        public bool EnableResume { get; set; } = true;

        /// <summary>
        /// 是否创建备份
        /// </summary>
        public bool CreateBackup { get; set; } = false;

        /// <summary>
        /// 备份位置
        /// </summary>
        public string BackupLocation { get; set; }

        /// <summary>
        /// 通知配置
        /// </summary>
        public TemplateNotificationConfig NotificationConfig { get; set; } = new();
    }

    /// <summary>
    /// 模板通知配置
    /// </summary>
    public class TemplateNotificationConfig
    {
        /// <summary>
        /// 开始时通知
        /// </summary>
        public bool NotifyOnStart { get; set; } = false;

        /// <summary>
        /// 完成时通知
        /// </summary>
        public bool NotifyOnCompletion { get; set; } = true;

        /// <summary>
        /// 失败时通知
        /// </summary>
        public bool NotifyOnFailure { get; set; } = true;

        /// <summary>
        /// 步骤完成时通知
        /// </summary>
        public bool NotifyOnStepCompletion { get; set; } = false;
    }

    /// <summary>
    /// 模板使用统计
    /// </summary>
    public class TemplateUsage
    {
        /// <summary>
        /// 总使用次数
        /// </summary>
        public int TotalUsageCount { get; set; }

        /// <summary>
        /// 成功使用次数
        /// </summary>
        public int SuccessCount { get; set; }

        /// <summary>
        /// 失败使用次数
        /// </summary>
        public int FailureCount { get; set; }

        /// <summary>
        /// 最后使用时间
        /// </summary>
        public DateTime? LastUsedTime { get; set; }

        /// <summary>
        /// 平均执行时间（毫秒）
        /// </summary>
        public double AverageExecutionTimeMs { get; set; }

        /// <summary>
        /// 使用用户列表
        /// </summary>
        public List<string> UsedByUsers { get; set; } = new();

        /// <summary>
        /// 成功率
        /// </summary>
        public double SuccessRate => TotalUsageCount > 0 ? (double)SuccessCount / TotalUsageCount : 0;
    }
}